<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Axios</title>
  </head>
  <body>
    <script>
      // axios -> Axios.prototype.request -> dispatchRequest -> xhrAdapter
      function Axios(config) {
        this.defaults = config;
      }
      Axios.prototype.request = function (config) {
        let promise = Promise.resolve(config);

        // 拦截器

        let chain = [dispatchRequest, undefined];

        while (chain.length) {
          promise = promise.then(chain.shift(), chain.shift());
        }

        return promise;
      };

      // dispatchRequest
      function dispatchRequest(config) {
        return xhrAdapter(config).then(
          (response) => {
            // 处理响应数据 transformResponseData
            response.data = JSON.parse(response.data);

            return response;
          },
          (error) => {
            Promise.reject(error);
          }
        );
      }

      // xhrAdapter
      function xhrAdapter(config) {
        return new Promise((resolve, reject) => {
          let xhr = new XMLHttpRequest();

          xhr.open(config.method, config.url);
          xhr.send();

          xhr.onreadystatechange = function () {
            if (xhr.readyState === 4) {
              if (xhr.status == 200 && xhr.status < 300) {
                resolve({
                  config: config,
                  headers: xhr.getAllResponseHeaders(),
                  data: xhr.response,
                  request: xhr,
                  status: xhr.status,
                  statusText: xhr.statusText,
                });
              } else {
                reject(new Error("请求失败"));
              }
            }
          };
        });
      }

      // axios 等价于 Axios.prototype.request
      let axios = Axios.prototype.request.bind(null);

      axios({
        method: "get",
        url: "https://yesno.wtf/api",
      }).then((response) => {
        console.log(response);
      });
    </script>
  </body>
</html>
